# coding=utf-8
import logging
from uuid import uuid4
from datetime import datetime
from hashlib import md5
from common import orm
from common.utils.decorator import sql_wrapper
from common.utils.db import list_object, get, upsert, delete
from common.mch.model import MchAccount

_LOGGER = logging.getLogger('hydra')

DEFAULT_PASSWD = '123456'

_SALT = u"V!$#s*PY"


def encode_password(passwd):
    return md5(passwd.encode('utf-8') + _SALT).hexdigest()


@sql_wrapper
def get_mch(id):
    return get(MchAccount, id)


@sql_wrapper
def upsert_mch(info, id=None):
    return upsert(MchAccount, info, id)


@sql_wrapper
def create_mch(info, id=None):
    if 'password' not in info:
        info['password'] = encode_password(DEFAULT_PASSWD)
    if 'api_key' not in info or not info['api_key']:
        info['api_key'] = uuid4().hex
    return upsert(MchAccount, info, id)


@sql_wrapper
def list_mch(query_dct):
    return list_object(query_dct, MchAccount)


@sql_wrapper
def delete_mch(id):
    delete(MchAccount, id)


@sql_wrapper
def get_mch_name_dict():
    mchs = MchAccount.query.all()
    result = {}
    for mch in mchs:
        result[mch.id] = mch.name
    return result

@sql_wrapper
def get_company_only():
    companies = MchAccount.query.all()
    result = []
    for c in companies:
        data = {}
        data["key"] = c.id
        data["value"] = c.name
        result.append(data)
    return result

@sql_wrapper
def update_status(info, id=None):
    return upsert(MchAccount, info, id)